package com.zsc.wxm.ysh.anjo.house.task;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zsc.wxm.ysh.anjo.house.model.RequestLog;
import com.zsc.wxm.ysh.anjo.house.model.ViewRequest;
import com.zsc.wxm.ysh.anjo.house.service.RequestLogService;
import com.zsc.wxm.ysh.anjo.house.service.ViewRequestService;
import com.zsc.wxm.ysh.anjo.service.base.enums.resources.ViewRequestStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述：更新看房请求任务
 *
 * @author playmaker
 * @since 2021/3/9 22:15
 */
@Slf4j(topic = "更新看房请求任务")
@Component
public class UpdateViewRequestStatusTask {

    @Resource
    private ViewRequestService viewRequestService;

    @Resource
    private RequestLogService requestLogService;

    @Transactional(rollbackFor = Exception.class)
    @Scheduled(cron = "0 0 0/5 * * ?")
    public void updateStatus() {
        long startTime = System.currentTimeMillis();
        log.info("----UpdateViewRequestStatusTask----定时任务执行开始");
        //筛选出 '待看房' 的数据
        List<ViewRequest> list = viewRequestService.list(null)
                .stream()
                .filter(x -> x.getRequestStatus() == ViewRequestStatus.WAITE_VIEW.getValue())
                .collect(Collectors.toList());
        //更新看房状态为已完成
        if (CollUtil.isNotEmpty(list)) {
            list.forEach(x -> {
                LambdaUpdateWrapper<ViewRequest> wrapper = Wrappers.lambdaUpdate();
                wrapper.eq(ViewRequest::getId, x.getId()).set(ViewRequest::getRequestStatus, ViewRequestStatus.COMPLETED.getValue());
                viewRequestService.update(wrapper);
                RequestLog requestLog = new RequestLog();
                requestLog.setDesc("流程结束，状态更改时间：" + LocalDateTime.now());
                requestLog.setViewRequestId(x.getId());
                requestLog.setTitle("已完成");
                requestLogService.save(requestLog);
            });
        }
        log.info("----UpdateViewRequestStatusTask----定时任务执行完成，消耗的时间{}ms", System.currentTimeMillis() - startTime);

    }
}
